<template>
  <div>
     <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
       <!-- 消息提示 -->
    <el-alert
      :closable="false"
      title="消息提示的文案"
      type="info"
      center
      show-icon>
  </el-alert>
  <!-- 步骤条 -->
  <!-- 动态绑定:active="activeIndex"step索引 -->
  <el-steps :space="200" :active="activeIndex - 0" align-center  finish-status="success">
    <el-step title="基本信息">基本信息</el-step>
    <el-step title="商品参数">商品参数</el-step>
    <el-step title="商品属性">商品属性</el-step>
    <el-step title="商品图片">商品图片</el-step>
    <el-step title="商品内容">商品内容</el-step>
    <el-step title="完成">完成</el-step>
 </el-steps>
 <!-- 标签页 -->
 <!-- 我name双向绑定我step的索引name点击同步与activeIndex -->
    <el-form ref="addGoodsFormRef" label-position="top"   :model="addGoodsForm" :rules="addGoodsFormRules">
      <el-tabs  :before-leave="tabsBeforeLeave"  @tab-click="tabClik" tab-position="left" v-model="activeIndex">
      <el-tab-pane label="基本信息" name="0">
        <!-- 标题动态生成出来 -->
        <el-form-item label="商品名称"  prop="goods_name">
          <el-input v-model="addGoodsForm.goods_name"></el-input>
        </el-form-item>
         <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="addGoodsForm.goods_price" type="number"> </el-input>
        </el-form-item>
         <el-form-item prop="goods_weight" label="商品重量">
          <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
        </el-form-item>
         <el-form-item label="商品数量" prop="goods_number" type="number">
          <el-input v-model="addGoodsForm.goods_number"></el-input>
        </el-form-item>
         <el-form-item label="商品分类" prop="goods_number">
           <!-- 级联选择器 -->
           <el-cascader
            v-model="addGoodsForm.goods_cat"
            :options="goodsCate"
            :props="cascaderProps"
            @change="handleChange"></el-cascader>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="商品参数" name="1">
        <!-- label动态绑定我的文本（参数）每一项 -->
        <el-form-item  v-for="item in manyDate" :key="item.attr_id" :label="item.attr_name">
          <el-checkbox-group  v-model="item.attr_vals">
            <el-checkbox v-for="(item,index) in item.attr_vals" :key="index" :label="item"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="商品属性" name="2">
        <el-form-item v-for="item in onlyDate" :key="item.attr_id" :label="item.attr_name">
        <el-input v-model="item.attr_vals"></el-input>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="商品图片" name="3">
        <!-- upload组件 -->
        <!-- action 上传接口地址 -->
        <!-- :on-preview:点击进行预览触发 -->
        <!-- :on-success:上传图片成功之后 -->
        <el-upload
          class="upload-demo"
          :headers="uploadHeaders"
          action="http://liufusong.top:8888/api/private/v1/upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="uploadSuccess"
          list-type="picture">
          <!--  :on-success="uploadSuccess"监听上传成功钩子函数，内置的我们res形参来接受后台返回来的数据 -->
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane label="商品内容" name="4">
        <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
        <el-button style="margin-top: 20px" type="primary" @click="addGoods">添加商品</el-button>
      </el-tab-pane>
    </el-tabs>
    </el-form>
    </el-card>
    <el-dialog  :visible.sync="dialogTableVisible">
      <img style="width: 100%" :src="imgUrl">
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      dialogTableVisible: false,
      imgUrl: '',
      activeIndex: 0,
      // addGoodsForm绑定我表单数据
      addGoodsForm: {
        // 商品名字
        goods_name: '',
        // 商品价格
        goods_price: 0,
        // 商品重量
        goods_weight: 0,
        // 商品数量
        goods_number: 0,
        // 商品分类id
        goods_cat: [],
        // 商品图片的信息
        pics: [

        ],
        goods_introduce: '',
        attrs: []
      },
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2到 5 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 级联选择器数据
      goodsCate: [],
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        // 我渲染那个字段到页面
        value: 'cat_id'
        // 保存的是后台传过来cat_id,（一级会一个id两个会两个id）
      },
      // 接收动态参数
      manyDate: [],
      // 接受动态参数
      onlyDate: [],
      uploadHeaders: {
        // 获取本地sessionStorage的方法获得本地se数据
        Authorization: sessionStorage.getItem('token')
      }
    }
  },

  created () {
    this.getGoodsCate()
  },
  computed: {
    //  三级分类id
    cateId () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        return null
      }
      return this.addGoodsForm.goods_cat[2]
    }
  },
  methods: {
    // 获取商品分类参数
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.console.error('获取失败')
      this.goodsCate = res.data
    },
    handleChange () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    tabsBeforeLeave (activeName, oldname) {
      if (oldname === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请选择三级分类')
        return false
      }
    },
    async getGoodsparams (sel) {
      const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', {
        params: {
          sel: sel
        }
      })
      // attr_vals渲染页面参数
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      if (sel === 'many') {
        res.data.forEach(item => {
          // attr_vals每一项参数（三级分类id对应的参数）后台返回来的是字符串要转成数组方便操作
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(',')
          // 如果是一级二级分类就返回一个数组，因为返回空字符串，分割容易出问题，（空字符串也占有空间）
        })
        this.manyDate = res.data
      } else {
        this.onlyDate = res.data
      }
    },
    // many是静态参数
    tabClik () {
      if (this.activeIndex === '1') {
        this.getGoodsparams('many')
      } else if (this.activeIndex === '2') {
        this.getGoodsparams('only')
      }
    },
    // file我图片上传成功的信息
    handlePreview (file) {
      this.dialogTableVisible = true
      this.imgUrl = 'http://liufusong.top:8888/' + file.response.data.tmp_path
    },
    handleRemove (file) {
      const index = this.addGoodsForm.pics.findIndex(item => {
        console.log(file)
        console.log(this.addGoodsForm.pics)
        return item.pic === file.response.data.tem_path
      })
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 图片上传成功
    uploadSuccess (res) {
      console.log('图片上传成功')
      this.addGoodsForm.pics.push({
        pic: res.data.tem_path
      })
    },
    addGoods () {
      // 测试校验是否通过
      this.$refs.addGoodsFormRef.validate(async flag => {
        if (!flag) return this.$message.error('请完善基本信息必填项')
        // 后台要字符串，我们要数组，
        const form = cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        this.manyDate.forEach(item => {
          // attrs是后台要求存放接收的动态参数和静态参数，我们循环添加attr_id是页面参数的id，attr_value是参数名称
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals.join(',') })
        })
        this.onlyDate.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
        })
        console.log(form, this.addGoodsForm)
        const { data: res } = await this.$axios.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('创建失败')
        this.$message.success('创建成功')
        this.$router.push('/goods')
      })
      // json深拷贝
      // const form = JSON.parse(JSON.stringify(this.addGoodsForm))
    }
  }
}
</script>

<style scoped lang='less'>
.steps{
  margin: 20px auto;
}
/deep/.el-step__title{
  font-size: 12px;
}
.el-checkbox{
  margin-right: 0;
}
/deep/.ql-editor {
  height: 400px     ;
}
</style>
